package boardgamer.yavalath.client.animation;

import android.graphics.Canvas;
import android.graphics.LightingColorFilter;
import android.graphics.Paint;
import boardgamer.common.client.animation.Animation;
import boardgamer.yavalath.client.game.YavalathDrawableTile;
import boardgamer.yavalath.client.resources.ImageHandler;
import com.google.common.collect.Sets;

import java.util.Collection;
import java.util.HashSet;

/**
 * @author garysoed
 */
public class SuggestionAnimation extends Animation {
  
  private static final int PERIOD = 30;

  private static final int ALPHA_CHANGE = 255 * PERIOD / 1000;
  
  private final HashSet<YavalathDrawableTile> tiles;
  private final Paint paint;
  private boolean fadingIn = true;
  
  public SuggestionAnimation() {
    super(PERIOD);
    
    this.tiles = Sets.newHashSet();
    this.paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    this.paint.setAlpha(0);
  }
  
  public void setTiles(int color, Collection<YavalathDrawableTile> tiles) {
    this.tiles.clear();
    this.tiles.addAll(tiles);
    this.paint.setAlpha(0);
    this.paint.setColorFilter(new LightingColorFilter(color, 0));
    this.fadingIn = true;
  }

  @Override
  public void draw(Canvas canvas) {
    for (YavalathDrawableTile tile : tiles) {
      canvas.drawBitmap(ImageHandler.tile, null /* src */, tile.getBoundingRect(), paint);
    }
  }

  @Override
  public boolean isDead() {
    return false;
  }

  @Override
  protected void onPeriodic() {
    int alpha;
    if (fadingIn) {
      alpha = paint.getAlpha() + ALPHA_CHANGE;
      if (alpha > 255) {
        alpha = 255 * 2 - alpha;
        fadingIn = false;
      }
    } else {
      alpha = paint.getAlpha() - ALPHA_CHANGE;
      if (alpha < 0) {
        alpha = -alpha;
        fadingIn = true;
      }
    }
    paint.setAlpha(alpha);
  }
}
